<?php

require_once('database.inc.php');

function getAsocArr($table, $keyname, $dataname, $dbh, $sort = false) {
	if (!$sort) $sort = "$dataname ASC";
	$retarr = array();
	$data = mysql_query("SELECT * FROM $table ORDER BY $sort", $dbh);
	while ($row = mysql_fetch_array($data)) {
		$retarr[$row[$keyname]] = $row[$dataname];
	}
	return $retarr;
}

function get_lastscandata($region) {
	$lastscan = $region['LastScan'];
	$retarr = array();
	$retarr['WeatherID'] = $region['Scans'][$lastscan]['WeatherID'];
	$retarr['TomorrowWeatherID'] = $region['Scans'][$lastscan]['TomorrowWeatherID'];
	$retarr['NumberOfUsers'] = $region['Scans'][$lastscan]['NumberOfUsers'];
	$retarr['NumberOfOnline'] = $region['Scans'][$lastscan]['NumberOfOnline'];
	return $retarr;
}

function get_onlineusers($country) {
	$n = 0;
	foreach ($country['Regions'] as $region) {
		$lastdata = get_lastscandata($region);
		$n += $lastdata['NumberOfOnline'];
	}
	return $n;
}

function getcountryinfo($leagueid, $dbh) {
	$result = mysql_query("SELECT * FROM leagues_daily WHERE leagueid = $leagueid LIMIT 1", $dbh);
	while ($data=mysql_fetch_array($result)) {
		$country['LeagueID'] 		= $leagueid;
		$country['LeagueName'] 		= $data['LeagueName'];
		$country['Season'] 		= $data['Season'];
		$country['MatchRound'] 		= $data['MatchRound'];
		$country['ShortName'] 		= $data['ShortName'];
		$country['Continent'] 		= $data['Continent'];
		$country['ZoneName'] 		= $data['ZoneName'];
		$country['EnglishName'] 	= $data['EnglishName'];
		$country['CurrencyName'] 	= $data['CurrencyName'];
		$country['CurrencyRate'] 	= $data['CurrencyRate'];
		$country['CupID'] 		= $data['CupID'];
		$country['CupName'] 		= $data['CupName'];
		$country['ActiveUsers'] 	= $data['ActiveUsers'];
		$country['WaitingUsers'] 	= $data['WaitingUsers'];
		$country['TrainingDate'] 	= $data['TrainingDate'];
		$country['EconomyDate']		= $data['EconomyDate'];
		$country['CupMatchDate'] 	= $data['CupMatchDate'];
		$country['SeriesMatchDate'] 	= $data['SeriesMatchDate'];
		$country['NumberOfLevels'] 	= $data['NumberOfLevels'];
	}
	return $country;
}

function getregions($leagueid, $dbh, &$firstscan, &$lastscan) {
	$regions = array();
	$yesterday = date("Y-m-d H:00:00", (time() - 86400));
	$now = date("Y-m-d H:i:s", time());
	if ($leagueid == 0) $result = mysql_query("SELECT * FROM regions ORDER BY RegionID", $dbh);
	else $result = mysql_query("SELECT * FROM regions WHERE LeagueID = $leagueid ORDER BY RegionID", $dbh);
	while ($region=mysql_fetch_array($result)) {
		$regions[$region['RegionID']] = array();
		$regions[$region['RegionID']]['RegionName'] = $region['RegionName'];
		$regions[$region['RegionID']]['Scans'] = getscans($region['RegionID'], $yesterday, $now, $dbh, $regions[$region['RegionID']]['FirstScan'], $regions[$region['RegionID']]['LastScan']);
		if ($regions[$region['RegionID']]['LastScan'] > $lastscan) {
			$lastscan = $regions[$region['RegionID']]['LastScan'];
		}
		if (is_null($firstscan) or $regions[$region['RegionID']]['FirstScan'] < $firstscan) {
			$firstscan = $regions[$region['RegionID']]['FirstScan'];
		}
	}
	return $regions;
}

function getscans($regionid, $from, $until, $dbh, &$firstscan, &$lastscan) {
	$regionscans = array();
	$result3 = mysql_query("SELECT * FROM maptrick WHERE RegionID = $regionid AND FetchedDate > '$from' AND FetchedDate <= '$until' ORDER BY ScanID ASC");
	while ($regiondata=mysql_fetch_array($result3)) {
		if (is_null($firstscan)) $firstscan = $regiondata['ScanID'];
		$lastscan = $regiondata['ScanID'];
		$regionscans[$regiondata['ScanID']] 				= array();
		$regionscans[$regiondata['ScanID']]['WeatherID'] 		= $regiondata['WeatherID'];
		$regionscans[$regiondata['ScanID']]['TomorrowWeatherID'] 	= $regiondata['TomorrowWeatherID'];
		$regionscans[$regiondata['ScanID']]['NumberOfUsers'] 		= $regiondata['NumberOfUsers'];
		$regionscans[$regiondata['ScanID']]['NumberOfOnline'] 		= $regiondata['NumberOfOnline'];
		$regionscans[$regiondata['ScanID']]['FetchedDate'] 		= $regiondata['FetchedDate'];
	}
	return $regionscans;
}


function getworldarray($dbh) {
	$world = array();

	$world['LeagueName'] = "World";
	$world['ShortName'] = "World";
	$world['EnglishName'] = "World";
	$world['Continent'] = "All";
	$world['ZoneName'] = "All";
	$world['NumberOfLevels'] = array();
	$world['ActiveUsers'] = 0;
	$world['WaitingUsers'] = 0;
	$world['NumberOfLevels'] = array();
	
	$result = mysql_query("SELECT * FROM leagues_daily", $dbh);
	while($data = mysql_fetch_array($result)) {
		$world['ActiveUsers'] += $data['ActiveUsers'];
		$world['WaitingUsers'] += $data['WaitingUsers'];
		$world['NumberOfLevels'][$data['NumberOfLevels']]++;
	}
	
	$world['Regions'] = getregions(0, $dbh, $world['VeryFirstScan'], $world['VeryLastScan']);

	return $world;
}


function getleaguearray($leagueid, $dbh) {
	$country = getcountryinfo($leagueid, $dbh);
	$country['Regions'] = getregions($leagueid, $dbh, $country['VeryFirstScan'], $country['VeryLastScan']);
	return $country;
}

function interpolate_missing_scans($region, $firstscan, $lastscan) {
	
	if (!isset ($region['Scans'][$firstscan])) {
		$region['Scans'][$firstscan] = array();
		$region['Scans'][$firstscan]['Interpolated'] = true;
		$good = $lastscan;
		while (!isset ($region['Scans'][$good])) {
			$good--;
		}
		$region['Scans'][$firstscan]['NumberOfOnline'] = $region['Scans'][$good]['NumberOfOnline'];
		$region['Scans'][$firstscan]['NumberOfUsers'] = $region['Scans'][$good]['NumberOfUsers'];
	}

	if (!isset ($region['Scans'][$lastscan])) {
		$region['Scans'][$lastscan] = array();
		$region['Scans'][$lastscan]['Interpolated'] = true;
		$good = $firstscan;
		while (!isset ($region['Scans'][$good])) {
			$good++;
		}
		//$region['Scans'][$lastscan]['NumberOfOnline'] = $region['Scans'][$good]['NumberOfOnline'];
		//$region['Scans'][$lastscan]['NumberOfUsers'] = $region['Scans'][$good]['NumberOfUsers'];
		$region['Scans'][$lastscan]['NumberOfOnline'] = 0;
		$region['Scans'][$lastscan]['NumberOfUsers'] = 0;

	}

	for ($i = $firstscan+1; $i <= $lastscan-1; $i++) {
		if (!isset ($region['Scans'][$i])) {
			$region['Scans'][$i] = array();
			$region['Scans'][$i]['Interpolated'] = true;
			$nextgood = $i+1;
			$prevgood = $i-1;
			while(!isset ($region['Scans'][$nextgood])) {
				$nextgood++;
			}
			$diff = ($nextgood - $i) + 1;
			
			$numberofusersprev = $region['Scans'][$prevgood]['NumberOfUsers'];
			$numberofonlineprev = $region['Scans'][$prevgood]['NumberOfOnline'];
			$numberofusersnext = $region['Scans'][$nextgood]['NumberOfUsers'];
			$numberofonlinenext = $region['Scans'][$nextgood]['NumberOfOnline'];
			
			$numberofusersdiff = $numberofusersnext - $numberofusersprev;
			$numberofonlinediff = $numberofonlinenext - $numberofonlineprev;
			
			$region['Scans'][$i]['NumberOfUsers'] = round($numberofusersprev + ($numberofusersdiff / $diff));
			$region['Scans'][$i]['NumberOfOnline'] = round($numberofonlineprev + ($numberofonlinediff/$diff));

		}
	}
	return $region;
}

function levels2teams($levels) {
#	$numusers = array(0, 8, 40, 168, 680, 2728, 10920, 19112, 27304, 35496, 43688, 51880, 60072);
	$numusers = array(0, 8, 40, 168, 680, 2728, 10920, 19112, 35496, 51880, 84648, 117416, 182952, 248488, 314024, 379560);
	return $numusers[$levels];
}

function nice_dump($var) {
	echo "<pre>\n";
	var_dump($var);
	echo "</pre>\n";
}

function updateHoc($teamid, $client, $dbh) {
	$now = date("Y-m-d H:i:s");
	$query = mysql_query("SELECT userid, fetcheddate FROM flags_updated WHERE teamid = $teamid", $dbh) or die (mysql_error());
	if (mysql_num_rows($query) == 1) {
		$flags = $client->getFlags($teamid, $row['fetcheddate']);
		if ($row['userid'] != $flags['info']['userid']) $flags = $client->getFlags($teamid);
	} else {
		$flags = $client->getFlags($teamid);
	}
	if (!isset($flags['info']['userid'])) {
		echo "Download for $teamid failed!\n";
		return(false);
	} else if ($flags['info']['teamid'] == 0) {
		echo "$teamid does not exist!\n";
		return(false);
	} else if ($flags['info']['userid'] == 0) {
		mysql_query("DELETE FROM flags_updated WHERE teamid = {$flags['info']['teamid']}", $dbh);
        mysql_query("DELETE FROM flags_v3 WHERE userid = {$flags['info']['userid']}", $dbh);
#		echo "$teamid is bot, removed.\n";
		return(-1);
	} else {
		$query = mysql_query("SELECT SUM(activeusers) AS active FROM leagues_daily WHERE leagueid != 255", $dbh);
		while ($row = mysql_fetch_array($query)) {
			$numactive = $row['active'];
		}
		if (!$lquery = mysql_query("SELECT leagueid FROM leagues_daily WHERE leagueid != 255", $dbh)) die (mysql_error());
		while ($lrow = mysql_fetch_array($lquery)) {
			mysql_query("INSERT IGNORE INTO flags_v3 VALUES ({$flags['info']['userid']}, {$lrow['leagueid']}, 0, 0)", $dbh);
		}
		foreach (array_keys($flags['away']) as $flag) {
			mysql_query("UPDATE flags_v3 SET away = 1 WHERE userid = '{$flags['info']['userid']}' AND legueid = '{$lrow['leagueid']}'", $dbh);
		}
		foreach (array_keys($flags['home']) as $flag) {
			mysql_query("UPDATE flags_v3 SET home = 1 WHERE userid = '{$flags['info']['userid']}' AND legueid = '{$lrow['leagueid']}'", $dbh);
		}
	
		if (!mysql_query("REPLACE INTO flags_updated VALUES (
			{$flags['info']['teamid']},\"" . 
			mysql_real_escape_string($flags['info']['teamname'],$dbh) . "\", 
			{$flags['info']['leagueid']},
			{$flags['info']['regionid']},
			{$flags['info']['userid']},
			\"{$flags['info']['loginname']}\",
			{$flags['info']['serieid']},
			{$flags['info']['hassupporter']},
			{$flags['info']['languageid']},
			{$flags['info']['stillincup']},
			\"{$flags['info']['signupdate']}\",
			\"{$flags['info']['activationdate']}\",
			\"{$flags['info']['lastlogindate']}\",
			\"{$flags['info']['fetcheddate']}\"
		)", $dbh)) die(mysql_error());
	
		return($flags['info']['userid']);
	}
}

function showHocRankBox($forteamid,$dbm) {

	$chasetypes = array(
		"0" => "Away",
		"1" => "Home",
		"2" => "Away AND Home",
		"3" => "Away PLUS Home"
	);

	$sorts = array("coolness", "num");

	if ($forteamid > 0) {
		$query = mysql_query("SELECT * FROM flags_updated WHERE teamid = $forteamid", $dbm) or die (mysql_error());
		if (mysql_num_rows($query) > 0) {
			$row = mysql_fetch_array($query);
			$userid = $row['UserID'];
			$leagueid = $row['LeagueID'];
			echo "<b>Ranking positions in the <a href=\"hallofcool.php\">Hall of Cool</a> for team $forteamid:</b><br />";
			echo "<table border=\"1\">\n";
			echo "<tr><th rowspan=\"2\">category<th colspan=\"2\">global<th colspan=\"2\"><img src=\"http://flags.alltidhattrick.org/images/{$leagueid}flag.gif\" border=\"1\"> national\n";
			echo "<tr><th>coolness<th>#flags<th>coolness<th>#flags\n";
			for ($i = 0; $i <= 3; $i++) {
				echo "<tr><th>{$chasetypes[$i]}";
				$query = mysql_query(
					"SELECT *
					FROM flags_ranking
					WHERE userid = $userid
					AND home = $i", $dbm
				) or die (mysql_error());
				if (mysql_num_rows($query) > 0) {
					$row = mysql_fetch_array($query);
					$coolness = $row['coolness'];
					$nflags = $row['num'];
					$query = mysql_query(
						"SELECT COUNT(*) + 1 cnt
						FROM flags_ranking
						WHERE home = $i
						AND ((coolness > $coolness) || (coolness = $coolness && num > $nflags))", $dbm
					) or die (mysql_error());
					if (mysql_num_rows($query) > 0) {
						$row = mysql_fetch_array($query);
						$start = $row['cnt'] - 10;
						if ($start < 1) $start = 1;
						echo "<td><a href=\"hallofcool.php?hosted=$i&numflags=0&start=$start&max=21\">{$row['cnt']}";
					} else {
						echo "<td>DNQ";
					}
					$query = mysql_query(
						"SELECT COUNT(*) + 1 cnt
						FROM flags_ranking
						WHERE home = $i
						AND ((num > $nflags) || (num = $nflags && coolness > $coolness))", $dbm
					) or die (mysql_error());
					if (mysql_num_rows($query) > 0) {
						$row = mysql_fetch_array($query);
						$start = $row['cnt'] - 10;
						if ($start < 1) $start = 1;
						echo "<td><a href=\"hallofcool.php?hosted=$i&numflags=1&start=$start&max=21\">{$row['cnt']}";
					} else {
						echo "<td>DNQ\n";
					}
					
					$query = mysql_query(
						"SELECT COUNT(*) + 1 cnt
						FROM flags_ranking, flags_updated
						WHERE flags_ranking.userid = flags_updated.userid
						AND flags_updated.leagueid = $leagueid
						AND home = $i
						AND ((coolness > $coolness) || (coolness = $coolness && num > $nflags))", $dbm
					) or die (mysql_error());
					if (mysql_num_rows($query) > 0) {
						$row = mysql_fetch_array($query);
						$start = $row['cnt'] - 10;
						if ($start < 1) $start = 1;
						echo "<td><a href=\"hallofcool.php?hosted=$i&numflags=0&start=$start&max=21&leagueid=$leagueid\">{$row['cnt']}";
					} else {
						echo "<td>DNQ";
					}
					$query = mysql_query(
						"SELECT COUNT(*) + 1 cnt
						FROM flags_ranking, flags_updated
						WHERE flags_ranking.userid = flags_updated.userid
						AND flags_updated.leagueid = $leagueid
						AND home = $i
						AND ((num > $nflags) || (num = $nflags && coolness > $coolness))", $dbm
					) or die (mysql_error());
					if (mysql_num_rows($query) > 0) {
						$row = mysql_fetch_array($query);
						$start = $row['cnt'] - 10;
						if ($start < 1) $start = 1;
						echo "<td><a href=\"hallofcool.php?hosted=$i&numflags=1&start=$start&max=21&leagueid=$leagueid\">{$row['cnt']}";
					} else {
						echo "<td>DNQ\n";
					}
					
				} else {
					echo "<td>N/A<td>N/A<td>N/A<td>N/A\n";
				}
			}
			echo "</table><br />\n";
		}
	}
}

function getLastUpdate() {
	return("2007-09-05");
}

function getUpdates() {
	$lastupdate = getLastUpdate();
	$updates = array(
		"2006-04-26",
#		"2006-05-16",
		"2006-06-05",
		"2006-08-08",
#		"2006-08-30",
#		"2006-09-18",
#		"2006-10-12",
#		"2006-10-31",
		"2006-11-21",
		"2006-12-12",
#		"2007-01-05",
#		"2007-01-22",
#		"2007-02-12",
		"2007-03-08",
		"2007-03-29",
#		"2007-04-17",
#		"2007-05-09",
#		"2007-06-04",
		"2007-06-25",
		"2007-07-17",
#		"2007-08-06",
		$lastupdate
	);

	return($updates);
}

function getAllUpdates() {
	$lastupdate = getLastUpdate();
	$updates = array(
		"2006-04-26",
		"2006-05-16",
		"2006-06-05",
		"2006-08-08",
		"2006-08-30",
		"2006-09-18",
		"2006-10-12",
		"2006-10-31",
		"2006-11-21",
		"2006-12-12",
		"2007-01-05",
		"2007-01-22",
		"2007-02-12",
		"2007-03-08",
		"2007-03-29",
		"2007-04-17",
		"2007-05-09",
		"2007-06-04",
		"2007-06-25",
		"2007-07-17",
		"2007-08-06",
		$lastupdate
	);

	return($updates);
}

?>
